﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ScoreofParentheses
{
    public class Solution
    {
        class Item
        {
            public Item(char symbol, int value, bool hasChildren = false)
            {
                this.Symbol = symbol;
                this.Value = value;
                this.HasChildren = hasChildren;
            }
            public char Symbol { get; set; }
            public int Value { get; set; }

            public bool HasChildren { get; set; }
        }
        public int ScoreOfParentheses(string S)
        {
            var list = new List<Item>();
            int sum = 0;
            foreach (var c in S)
            {
                if (c == '(')
                {
                    if (list.Count > 0)
                    {
                        list[list.Count - 1].HasChildren = true;
                    }

                    list.Add(new Item(c, 1));
                }
                else
                {
                    var peek = list[list.Count - 1];
                    list.RemoveAt(list.Count - 1);
                    if (list.Count == 0)
                    {
                        sum += peek.Value == 1 ? 1 : peek.Value * 2;
                    }
                    else if (list[list.Count - 1].HasChildren)
                    {
                        list[list.Count - 1].Value = peek.Value * 2;
                    }
                    else
                    {
                        list[list.Count - 1].Value += 1;
                    }
                }
            }

            return sum;
        }
    }
}
